package cn.tpshion.vm.handler.task.support;

import cn.tpshion.vm.common.constant.MsgType;
import cn.tpshion.vm.domain.support.MsgData;
import cn.tpshion.vm.domain.support.NodeContext;
import cn.tpshion.vm.handler.SSEHandle;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jgit.lib.ProgressMonitor;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class MsgProgressMonitor implements ProgressMonitor {

    private AtomicInteger atomicInteger = new AtomicInteger();

    private int totalTasks;

    private SSEHandle sseHandle;

    private NodeContext nodeContext;

    public MsgProgressMonitor(NodeContext nodeContext, SSEHandle sseHandle){
        this.nodeContext = nodeContext;
        this.sseHandle = sseHandle;
    }

    @Override
    public void start(int totalTasks) {
        this.totalTasks = totalTasks;
        String msg = "git clone work on " + totalTasks + " tasks";
        log.info(msg);
        sseHandle.sendMessage(nodeContext, MsgData.of(MsgType.INFO, msg));
    }

    @Override
    public void beginTask(String title, int totalWork) {
        String msg = "starting work " + title + " on " + totalWork + " tasks";
        log.info(msg);
        sseHandle.sendMessage(nodeContext, MsgData.of(MsgType.INFO, msg));
    }

    @Override
    public void update(int completed) {
        int num = atomicInteger.addAndGet(completed);
        String msg = "update work tasks: " + num + "/" + totalTasks;
        log.info(msg);
        sseHandle.sendMessage(nodeContext, MsgData.of(MsgType.INFO, msg));
    }

    @Override
    public void endTask() {

    }

    @Override
    public boolean isCancelled() {
        return false;
    }

    @Override
    public void showDuration(boolean b) {

    }
}
